from django.conf import settings
from backend.gnsuser.gnsuser import GnsuserAPI
from django.contrib.auth import get_user_model

User = get_user_model()

user_api = settings.GNS_USER_API

def get_user_by_qrcode(qrcode:str):
    '''
        get user by qrcode from gnsuser module
    '''
    
    data,res = user_api.getItemByID(qrcode=qrcode,no_cache=True)
    
    print(data)
    
    if 'cews' not in data:
        return False
    
    user_dict = data['cews']
    user_id = user_dict['userid']
    
    user_model = User.objects.filter(id=user_id).first()
    
    if not user_model:
        return False
    
    return user_model


class CheckState():
    _ENDORSE = 'endorse'
    _VERIFY = 'verify'
    _DELETE = 'delete'
    _RESET= 'reset'
    _RESET_ENDORSED= 'reset_endorsed'
    


def resetEformCheckState(eform):
    """
        Set done, verify, endorse date to none,
        set verifyed_id , endorsedby_id to None
    """
    eform.verifiedby_id = None
    eform.endorsedby_id = None
    eform.doneDate = None
    eform.verifiedDate = None
    eform.endorsedDate = None
    eform.save()


def checkCanEndorse(user):
    """
        return {bool}, permission to perform endrose 
    """
    return user.has_perm('eform.can_endorsed')


def checkCanVerify(user):
    """
        return {bool}, permission to perform verify 
    """
    return user.has_perm('eform.can_verified')

def checkCanDelete(user):
    """
        return {bool}, permission to perform delete
    """
    return user.has_perm('eform.delete_eform')

def getCheckFunction(check_state):
    """
    @params {String} check_state, verify|endrose
    RETURN suitable checkfunction {checkCanEndorse | checkCanVerify}
    """
    if not check_state:
        return False
    
    if check_state == CheckState._VERIFY:
        return checkCanVerify
    
    if check_state == CheckState._ENDORSE:
        return checkCanEndorse

    if check_state == CheckState._DELETE:
        return checkCanDelete
    
    if check_state == CheckState._RESET:
        return checkCanReset

    if check_state == CheckState._RESET_ENDORSED:
        return checkCanResetEndorsed
    return False

def checkCanResetEndorsed(user):
    return user.has_perm('eform.can_reset_endorsed')

def checkCanReset(user):
    """ Every one can reset the form if the form is not verified"""
    return True